package info.mrchen.gae.weibo2mail.dao;

import info.mrchen.gae.weibo2mail.pojo.SavedAccessToken;

import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

import org.springframework.stereotype.Component;

import twitter4j.auth.AccessToken;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.users.User;

@Component
public class TwitterWeiboDao {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

    public void saveAccessToken(AccessToken accessToken4Twitter, User owner) {
        SavedAccessToken accessToken = convert(accessToken4Twitter);
        accessToken.setOwner(owner);
        try {
            pm.makePersistent(accessToken);
        } finally {
            pm.close();
        }
    }

    private SavedAccessToken convert(AccessToken accessToken4Twitter) {
        SavedAccessToken savedAccessToken = new SavedAccessToken();
        savedAccessToken.setToken(accessToken4Twitter.getToken());
        savedAccessToken.setTokenSecret(accessToken4Twitter.getTokenSecret());
        savedAccessToken.setCreateAt(new Date());
        return savedAccessToken;
    }

    public List<SavedAccessToken> getAccount(User currentUser) {
        String query = "owner = _owner";
        javax.jdo.Query query2 = pm.newQuery(SavedAccessToken.class, query);
        query2.declareParameters("_owner");
        return (List<SavedAccessToken>) query2.execute(currentUser);
    }

}